module.exports = {
  /**
   * 用户登录(微信授权)
   * @url user/pub/loginByWeixin 前端调用的url参数地址
   * @description 用户登录(微信授权)
	 * data 请求参数 说明
	 * @param {String} code 微信登录返回的code
	 * @param {String} platform 客户端类型：mp-weixin、app-plus，默认uni-id会自动取客户端类型，但是在云函数url化等场景无法取到客户端类型，可以使用此参数指定
	 * @param {String} type login:登录 register:注册
	 * res 返回参数说明
	 * @param {Number} code 错误码，0表示成功
	 * @param {String} msg 详细信息
	 * @param {String} token 登录成功之后返回的token信息
	 * @param {String} tokenExpired token过期时间
   */
	main: async (event) => {
		let { data = {}, util, originalParam } = event;
		let { uniID, config, pubFun, vk , db, _ } = util;
		let { uid } = data;
		let res = { code: 0, msg: '' };
		// 业务逻辑开始-----------------------------------------------------------
		let info = await uniID.loginByWeixin(data);
		if(info.token){
			let user = {}
			if(info.type === "register"){
				var score = 0
				//查询积分配置
				var signScore = await vk.baseDao.findByWhereJson({
					dbName: 'bus-wx-config',
					whereJson: {
						config_key: 'score_config'
					}
				});
				if(signScore && signScore.register_score > 0){
					score = signScore.register_score
					// 添加积分记录
					var scoreNum = await vk.baseDao.add({
						dbName: "uni-id-scores",
						dataJson: {
							user_id: info.uid,
							type: 1,
							score: score,
							balance: score,
							comment: '首次注册'
						}
					});
				}
				// 邀请码
				var inviter_uid
				var inviter_time
				if(data.inviteCode){
					inviter_uid = data.inviteCode
					inviter_time = new Date().getTime()
					res.register = true
				}
				user = await vk.baseDao.updateById({
					dbName: 'uni-id-users',
					id: info.uid,
					dataJson: {
						nickname: data.nickname,
						gender: data.gender,
						avatar: data.avatarUrl,
						status: 0,
						score: score,
						price: 0,
						inviter_uid,
						inviter_time,
						origin: 'wx'
					},
					getUpdateData:true
				});
				res.msg = user.nickname+'，恭喜注册成功！'
			}else{
				user = await vk.baseDao.updateById({
					dbName: 'uni-id-users',
					id: info.uid,
					dataJson: {
						nickname: data.nickname,
						gender: data.gender,
						avatar: data.avatarUrl,
						origin: 'wx'
					},
					getUpdateData:true
				});
				res.msg = user.nickname+'，欢迎回来！'
			}
			
			res.userInfo = user
			res.vk_uni_token = info.vk_uni_token
			res.token= info.token
			res.tokenExpired= info.tokenExpired
			
			// 日志服务
			const loginLogService = vk.require("service/user/util/login_log");
			await loginLogService.add({
				type: "login",
				login_type: "sx",
				user_id: info.uid,
				context: originalParam.context
			},util);
		}
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}